package com.demo2do.fms.admin.web.controller.business;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.report.ExportType;
import com.demo2do.fms.admin.entity.report.business.TransOrderReportSearch;
import com.demo2do.fms.admin.entity.search.business.TransOrderSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.business.BalanceService;
import com.demo2do.fms.admin.service.business.DispatchOrderService;
import com.demo2do.fms.admin.service.business.ShipmentService;
import com.demo2do.fms.admin.utils.FormatUtils;
import com.demo2do.fms.admin.visitor.impl.PersistentVisitor;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.admin.web.view.ExcelTemplateView;
import com.demo2do.fms.entity.business.shipment.DispatchOrder;
import com.demo2do.fms.entity.business.shipment.ShipmentOrder;

/**
 * 回单确认 
 *
 * @author Ark
 *
 */
@Controller
@RequestMapping(value = "/trans-orders")
@MenuSetting("menu-business")
public class TransOrderController {

    private static final Logger logger = LoggerFactory.getLogger(TransOrderController.class);
    
    @Autowired
    private DispatchOrderService dispatchOrderService;
    
    @Autowired
    private ShipmentService shipmentService;
    
    @Autowired
    private BalanceService balanceService;
    
    @Autowired
    private PersistentVisitor persistentVisitor;
    
    /**
     * 回单确认 - 查询界面  
     * 
     * @param login
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @MenuSetting("submenu-trans-order")
    public ModelAndView search(@Secure Login login){

        ModelAndView modelAndView = new ModelAndView("business/trans-order/trans-order-search");
        
        modelAndView.addObject("region", login.isRegionUser());
        modelAndView.addObject("orgIds", login.getCurrOrgIds());
        
        return modelAndView;
        
    }
    
    /**
     * 回单确认 - 确认查询
     * 
     * @param search
     * @param page
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params= "filter")
    @MenuSetting("submenu-trans-order")
    public ModelAndView onSearch(TransOrderSearch search, Page page, 
                                 HttpServletRequest request, HttpSession session){

        ModelAndView modelAndView = new ModelAndView("business/trans-order/trans-order-list");
        
        session.setAttribute("transOrderQueryString", request.getQueryString());
        
        int totals = dispatchOrderService.countTransOrder(search);
        if(totals > 0){
            
            List<DispatchOrder> dispatchOrders = dispatchOrderService.listTransOrder(search, page.with(totals));
            
            modelAndView.addObject("dispatchOrders", dispatchOrders);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 回单确认 - 确认页
     * 
     * @param dispatchOrderId
     * @return
     */
    @RequestMapping(value = "/{id}/confirm", method = RequestMethod.GET)
    @MenuSetting("submenu-trans-order")
    public ModelAndView confirm(@PathVariable("id") Long dispatchOrderId){

        ModelAndView modelAndView = new ModelAndView("business/trans-order/trans-order-confirm");
        
        // 1. load diapatch_order by id
        DispatchOrder dispatchOrder = dispatchOrderService.loadDispatchOrder(dispatchOrderId);
        modelAndView.addObject("dispatchOrder", dispatchOrder);
        
        // 2. list shipment_order by dispatch_order_id
        List<ShipmentOrder> shipmentOrders = shipmentService.listShipmentOrder(dispatchOrderId);
        modelAndView.addObject("shipmentOrders", shipmentOrders);
        
        return modelAndView;
        
    }
    
    /**
     * 回单确认 - 执行确认
     * 
     * @param operator
     * @param itemIds
     * @param itemQuantity
     * @param dispatchOrderId
     * @return
     */
    @RequestMapping(value = "/{id}/confirm", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-trans-order")
    public @ResponseBody HttpResult onConfirm(@Secure Login operator, 
                                              @PathVariable(value = "id") Long dispatchOrderId,
                                              @RequestParam(value = "itemIds") List<Long> itemIds, 
                                              @RequestParam(value = "itemQuantity") Integer itemQuantity){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // accomplish confirm
            balanceService.accomplishConfirm(dispatchOrderId, itemIds, itemQuantity, operator);
            
            httpResult.success().message("回单确认成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("回单确认失败");
            logger.error("#onConfirm() - shipment order confirm fail, exception is [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * 输出当前记录
     * 
     * @param search
     * @param page
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView export(TransOrderSearch search, Page page) {
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("business/trans-order-export.xlsx"));
        
        // 1. list dispatch_order
        int totals = dispatchOrderService.countTransOrder(search);
        if(totals > 0){
            List<DispatchOrder> dispatchOrders = dispatchOrderService.listTransOrder(search, page.with(totals));
            modelAndView.addObject("dispatchOrders", dispatchOrders);
        }
        
        // 2. attribute
        modelAndView.addObject("persist", persistentVisitor);
        modelAndView.addObject("type", ExportType.CURRENT);
        
        // 3. format util
        FormatUtils fmt = new FormatUtils();
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
        
    }
    
    /**
     * 输出所有记录
     * 
     * @param search
     * @return
     */
    @RequestMapping(value = "/export-all", method = RequestMethod.GET)
    public ModelAndView exportAll(TransOrderReportSearch search) {
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("business/trans-order-export.xlsx"));
        
        // 1. list result 
        List<Map<String, Object>> results = dispatchOrderService.exportAll(search);
        modelAndView.addObject("results", results);
        
        // 2. attribute
        modelAndView.addObject("type", ExportType.ALL);
        
        // 3. format util
        FormatUtils fmt = new FormatUtils();
        modelAndView.addObject("fmt", fmt);
        
        logger.warn("#exportAll() - export size=[{}]...", results.size());
        
        return modelAndView;
        
    }
    
}